//app.js// fljp928bkd  wx38e3ce9a3b64a91c
var rqcfg = require('./utils/constant.js');
var aldstat = require('./utils/san.js');
// import { request } from './utils/request.js'
const bgMusicAudioContext = wx.getBackgroundAudioManager();
const EARTH_RADIUS = 6378137.0;//单位m
var navigateTo = wx.navigateTo;
Object.defineProperty(wx, 'navigateTo', {
  configurable: true,
  enumerable: true,
  writable: true,
})

wx.navigateTo = function (data) {
  setTimeout(function () {
    navigateTo(data)
  }, 100)
}
App({
  data: {

  },
  globalData: {
    userInfo: null,
    plumSession: null,
    requestUrl: rqcfg.rqcfg.rqurl,
    domin: rqcfg.rqcfg.domin,
    shareInfo: '',
    sessionFailNum: 0,
    isLogining: false,  //正在登录中
    requestQueue: [],
    againRequestContact: false,
    isRequestMark: false,
    requestCartNum: -1,
    requestTmplIds: {}, //订阅ids全局变量
    saveTmplNum: 0, //全局触发保存订阅id的次数
    saveTmplArr: {} //要保存的订阅ids
  },
  onLaunch: function (e) {
    var that = this;
    console.log("场景值" + e.scene)
    if (e && e.scene) {
      var scene = e.scene;
      if (scene == '1007' || scene == '1008' || scene == '1047' || scene == '1048' || scene == '1049' || scene == '1043' || scene == '1058' || scene == '1067' || scene == '1074' || scene == '1082' || scene == '1091') {
        that.globalData.enterFrom = 'share';
      }
    }
    if (rqcfg.rqcfg.suid) {
      that.globalData.requestUrl = rqcfg.rqcfg.rqurl + 'suid=' + rqcfg.rqcfg.suid;
      rqcfg.rqcfg.rqurl = rqcfg.rqcfg.rqurl + 'suid=' + rqcfg.rqcfg.suid + '&appid=' + rqcfg.rqcfg.appid;

      // that.globalData.liverqurl = rqcfg.rqcfg.liverqurl + 'suid=' + rqcfg.rqcfg.suid; //用与直播请求链接
      rqcfg.rqcfg.liverqurl = rqcfg.rqcfg.liverqurl + 'suid=' + rqcfg.rqcfg.suid + '&appid=' + rqcfg.rqcfg.appid;

      that.globalData.suid = rqcfg.rqcfg.suid;
      that.globalData.appid = rqcfg.rqcfg.appid;
      that.globalData.version = rqcfg.rqcfg.version;
      // that.globalData.develop = true;
      // 微信授权获取信息
      // that.wechatSq();
    } else {
      let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
      if (extConfig) {
        console.log(extConfig);
        var suid = extConfig.suid;
        var version = extConfig.version;
        var base = extConfig.base;
        var appid = extConfig.appid ? extConfig.appid : '';
        that.globalData.menuTitle = extConfig.menu;
        that.globalData.pageviewlink = extConfig.pageviewlink;
        that.globalData.cartIndex = extConfig.cartIndex;
        rqcfg.rqcfg.rqurl = rqcfg.rqcfg.rqurl + 'suid=' + suid + '&appid=' + appid;
        rqcfg.rqcfg.liverqurl = rqcfg.rqcfg.liverqurl + 'suid=' + suid + '&appid=' + appid;
        that.globalData.requestUrl = rqcfg.rqcfg.rqurl;
        that.globalData.liverqurl = rqcfg.rqcfg.liverqurl; //用与直播请求链接
        that.globalData.suid = suid;
        that.globalData.appid = appid;
        that.globalData.version = version;
        that.globalData.base = base;
        that.globalData.navBgcolor = extConfig.navigationBarBackgroundColor;
        that.globalData.navTextStyle = extConfig.navigationBarTextStyle;
        that.globalData.indexUrl = extConfig.indexUrl;
        // 微信授权获取信息
        // that.wechatSq();
      }
    }
    wx.onAppHide(function () { //监听小程序切入后台
      that.toSaveSubId(); //当订阅id保存接口出发不大于10次且退出小程序时，保存订阅id
    })
  },
  onShow: function (e) {
    var that = this;
    console.log(e);
    console.log("场景值" + e.scene);
    if (e && e.query.scene) {  //接收成为分销商的参数
      that.globalData.scene = decodeURIComponent(e.query.scene);
    }
    if (!that.globalData.plumSession) {
      that.wechatSq(that, e);
      if (that.globalData.scene){
        that.globalData.requestQueue.push({
          page:that,
          fname: 'requestdistributionInfo'
        });
      }
      
    } else {
      if (that.globalData.nologin != 1) {
        that.isLogin(e);
      };
      if (that.globalData.scene) {
        that.requestdistributionInfo(that.globalData.scene);
      }
    }

  },
  //监听错误
  onError: function (msg) {
    var that = this;
    console.log('错误监听');
    var errorInfo = JSON.stringify(msg);
    console.log(errorInfo);
    that.postError(errorInfo); //错误发送
  },
  //传递错误信息到后台
  postError: function (error) {
    var that = this;
    var mobileInfo;
    var suid = that.globalData.suid ? that.globalData.suid : '';
    var appid = that.globalData.appid ? that.globalData.appid : '';
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        mobileInfo = res;
      }
    });
    var currentPage = getCurrentPages() ? getCurrentPages()[getCurrentPages().length - 1].route : ''; //获取当前页面链接
    console.log('获取当前页面链接');
    console.log(currentPage);
    var data = {};
    data.map = "applet_error_log";
    data.type = "营销商城";
    data.suid = suid;
    data.appid = appid;
    data.brand = mobileInfo.brand;
    data.model = mobileInfo.model;
    data.wxVersion = mobileInfo.version;
    data.SDKVersion = mobileInfo.SDKVersion;
    data.system = mobileInfo.system;
    data.error = error;
    data.currentPage = currentPage;
    console.log(data);
    wx.request({
      url: that.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log('错误发送成功');
          console.log(res.data);
        } else {
          console.log(res);
        }
      },
      fail: function () {
        console.log('失败');
      }
    });
  },
  // 深度拷贝对象
  deepClone: function (obj) {
    let objClone = JSON.parse(JSON.stringify(obj));
    return objClone
  },
  //成为分销商
  requestdistributionInfo: function (mid) {
    var that = this;
    console.log('成为分销商');
    console.log(mid);
    var data = {};
    data.map = 'applet_three_set_level_new';
    data.mid = mid ? mid:that.globalData.scene;   
    console.log(data);
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: that.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log('分销商信息', res.data);
        if (res.data.ec == 200) {
        } else {
          // that.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  getNavheight: function () {
    wx.getSystemInfo({
      success: res => {
        //导航高度
        this.globalData.statusBarHeight = res.statusBarHeight;
        this.globalData.navHeight = res.statusBarHeight + 46;
        console.log(this.globalData.navHeight + '////////' + res.statusBarHeight)
      }, fail(err) {
        console.log(err);
      }
    })
  },
  isLogin: function (e) {
    var _this = this;
    var path = '', jumpUrl = '';
    if (e && e.path) {
      var pathQuery = '?';
      for (var key in e.query) {
        pathQuery += key + '=' + e.query[key] + '&';
      }
      path = e.path + pathQuery;
      path = '/' + path.substr(0, path.length - 1);
      console.log(path);
      jumpUrl = path;
      path = encodeURIComponent(path);
    }
    // 判断是否验证
    var data = {
      map: 'applet_start_page'
    }
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data.data);
        var applyInfo = res.data.data;
        if (res.data.data.applyOpen == 1 && applyInfo.applyStatus != 2) {
          wx.reLaunch({
            url: '/pages/login/login?url=' + path,
          })
        } else {
          _this.globalData.nologin = 1;
        }
      },
      fail: function (res) {
        console.log(res.data);
      },
    });
  },

  getNewRequestUrl: function (mid) {
    var _this = this;
    var newUrl = rqcfg.rqcfg.rqurl;
    console.log("原链接----" + newUrl);
    var plumSession = _this.globalData.plumSession;
    newUrl = rqcfg.rqcfg.rqurl + '&plum_session_applet=' + plumSession;
    if (mid) {
      newUrl += '&mid=' + mid;
    }
    console.log("旧请求链接----" + _this.globalData.requestUrl);
    console.log("新请求链接----" + newUrl);
    return newUrl;
  },
  getPoint: function (that) {
    var _this = this;
    setTimeout(function () {
      wx.request({
        url: _this.globalData.requestUrl,
        data: {
          map: 'applet_share_get_point'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            if (res.data.data.msg) {
              console.log(res.data.data.msg);
              wx.showModal({
                title: '',
                content: res.data.data.msg,
                showCancel: false
              })
            }
          } else {
            if (res.data.em) {
              wx.showModal({
                title: '',
                content: res.data.em,
                showCancel: false
              })
            }
          }
        },
        complete: function () {
        }
      });
    }, 3000)
  },
  errorTip: function (that, text, timer) {
    console.log(that);
    that.setData({
      errorTip: {
        text: text,
        isShow: true
      }
    })
    setTimeout(function () {
      that.setData({
        errorTip: {
          text: '',
          isShow: false
        }
      })
    }, timer)
  },

  // 获取用户信息
  wechatSq: function (obj) {
    var that = this;
    if (obj && obj.page) {
      this.globalData.requestQueue.push(obj);
    }
    if (this.globalData.isLogining) return;  //若是正在登录
    this.globalData.isLogining = true;
    wx.showLoading({
      title: '加载中',
    })
    that.getLogincode()
    .then(res=>{
      return that.getPlumsession(res.code)
    })
    .then(res => {
      this.globalData.isLogining = false;
      if (res.data.ec == 200) {
        console.log("获取用户信息成功");
        let responseData = res.data.data;
        that.globalData.plumSession = responseData.plum_session_applet;
        
        that.globalData.requestUrl = rqcfg.rqcfg.rqurl + '&plum_session_applet=' + responseData.plum_session_applet;
        that.globalData.commonUrl = rqcfg.rqcfg.rqurl + '&plum_session_applet=' + responseData.plum_session_applet;
        that.globalData.liverqurl = rqcfg.rqcfg.liverqurl + '&plum_session_applet=' + responseData.plum_session_applet; //用与直播请求链接
        console.log(that.globalData.requestUrl);
        //由于这里是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (that.plumSessionCallback) {
          that.plumSessionCallback(responseData.plum_session_applet);
        }
        that.globalData.plumSession = responseData.plum_session_applet;
        that.globalData.slient = responseData.slient;
        that.globalData.iosShow = responseData.iosShow;
        that.globalData.isHasunionid = responseData.haveUnionid;
        that.globalData.haveVcmCard = responseData.haveVcmCard;

        var defaultAvatar = 'http://tiandiantong.oss-cn-beijing.aliyuncs.com/images/icon_photo.png';
        responseData.avatar = responseData.avatar ? responseData.avatar : defaultAvatar;
        responseData.nickname = responseData.nickname ? responseData.nickname : '用户昵称';
        that.globalData.userInfo = responseData;
        console.log(that.globalData.userInfo);
        if (responseData.haveUnionid == 0) {   //如果未获取到unionId
          wx.getUserInfo({
            success(res) {
              console.log('已经授权可以直接获取用户信息', res);
              that.getUnionid('', res);
            },
            fail(res) {
              console.log('用户还未授权');
            }
          })
        }
        let requestQueue = that.globalData.requestQueue;
        if (requestQueue.length > 0) {
          console.log(requestQueue)
          for (let fun of requestQueue) {
            console.log(fun)
            let pointer = fun.page;
            let fname = fun.fname;
            pointer[fname]()
          }
          that.globalData.requestQueue = []
        }
        that.getContactCfg();//客服配置
        setTimeout(function () { //2s之后获取订阅消息模板id
          that.getTmplIds();
        }, 1000)

      } else {
        console.log(res.data);
        console.log("获取用户信息失败");
        if (that.globalData.sessionFailNum < 3) {
          var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针
          that.globalData.sessionFailNum = that.globalData.sessionFailNum + 1;
          console.log('获取用户信息失败次数', that.globalData.sessionFailNum);
          that.wechatSq(page);

        } else {
          var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针
          page.setData({
            loginFail: true
          })
          that.postError(res.data.em + '登陆' + that.globalData.sessionFailNum + '次失败'); //错误发送
        }
      }
    }, err => {
      this.globalData.isLogining = false;
      console.log(err);
    })
  },
  // 获取login登录code
  getLogincode: function (){
    var that = this;
    return new Promise(function(resolve, reject){
      wx.login({
        success: function (res) {
          var code = res.code;
          if (res.code) {
            resolve(res)
          } else {
            that.postError(res.data.em);
            reject(res);
            wx.showToast({
              title: '获取用户登录态失败！' + res.errMsg,
              icon: 'none',
              duration: 2000
            })
          }
        },
        fail: function (res) {
          reject(res);
          wx.showToast({
            title: '用户code获取失败！' + res.errMsg,
            icon: 'none',
            duration: 2000
          })
        }
      });
    })
    
  },
  // 获取用户session
  getPlumsession: function (code) {
    var that = this;
    var data = {
      map: 'applet_member_info',
      code: code,
      slient: 1,
    }
    console.log(data);
    return new Promise(function (resolve, reject) {
      wx.request({
        url: rqcfg.rqcfg.rqurl,
        data: data,
        success: function (res) {
          resolve(res);
        }, 
        fail:function(res){
          reject(res);
        },
        complete: function () {
          console.log("执行完成");
          wx.hideLoading();
        }
      });
    })
  },
  getTmplIds: function () {
    var that = this;
    wx.request({
      url: that.globalData.requestUrl,
      data: {
        map: 'applet_subscribe_get_ids_all'
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log('订阅消息', res.data.data);
          that.globalData.requestTmplIds = res.data.data;
        } else {
          console.log(res);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  getuserInfo: function (obj, userdata, again) {
    var that = this;
    var info = that.globalData.userInfo;
    var userInfo = userdata.userInfo;	
	if(userInfo.gender==0){
		var sex ='未知';
	}else{
		var sex = userInfo.gender==2 ? '女':'男';
	}
	
    wx.login({
      success(reslogin) {
        if (reslogin.code) {
          var data = {
            map: 'applet_update_member_info',
            avatar: userInfo.avatarUrl,
            nickname: userInfo.nickName,
            sex: sex,
            city: userInfo.city,
            province: userInfo.province,
            iv: userdata.iv,
            encryptedData: userdata.encryptedData,
            code: reslogin.code
          }
          console.log(data);
          if (obj.data.isupdateLoading) return;
          obj.setData({
            isupdateLoading: true
          })
          //发起请求，获取列表列表
          wx.showLoading({
            title: '加载中',
          })
          wx.request({
            url: that.globalData.requestUrl,
            data: data,
            success: function (res) {
              console.log(res.data);
              if (res.data.ec == 200) {
                that.globalData.slient = '0';
                info.avatar = userInfo.avatarUrl;
                info.nickname = userInfo.nickName;
                info.sex = sex;
                that.globalData.userInfo = info;
                that.globalData.isHasunionid = 1;
                obj.setData({
                  userInfo: info,
                  slient: that.globalData.slient,
                  isHasunionid: that.globalData.isHasunionid,
                  isupdateLoading: false
                })
                wx.showTabBar();
                console.log(obj.data.slient);
                // obj.initPage();
                if (again) {
                  if (again == 'tomyGreet') {
                    obj[again]();
                  } else {
                    wx.showToast({
                      title: '同步成功',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                } else {
                  wx.hideLoading();
                }
              } else {
                app.errorTip(that, res.data.em, 2000);
              }
            },
            fail: function () {
              wx.hideLoading();
            }
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  makeCall: function () {
    var mobile = this.globalData.telphone;
    console.log(mobile);
    wx.showModal({
      title: '',
      content: mobile,
      confirmText: '拨打',
      confirmColor: '#48C23D',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")

            }
          })
        }
      }
    })
  },
  makeCallphone: function (mobile) {
    console.log(mobile);
    wx.showModal({
      title: '',
      content: mobile,
      confirmText: '拨打',
      confirmColor: '#48C23D',
      success: function (res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
              console.log("拨打电话成功！")
            },
            fail: function () {
              console.log("拨打电话失败！")

            }
          })
        }
      }
    })
  },
  setVersion: function (obj) {
    var that = this;
    obj.setData({
      curVersion: that.globalData.version ? that.globalData.version : '',
      watermark: that.globalData.watermark ? that.globalData.watermark : '',
      supportOpen: that.globalData.supportOpen ? that.globalData.supportOpen : '',
      supportMobile: that.globalData.supportMobile ? that.globalData.supportMobile : '',
      openWatermark: that.globalData.openWatermark ? that.globalData.openWatermark : '',
      watermarkLogo: that.globalData.watermarkLogo ? that.globalData.watermarkLogo : ''
    })
  },
  //跳转设置页面授权
  openSetting: function (again) {
    var that = this;
    if (wx.openSetting) {
      wx.openSetting({
        success: function (res) {
          res.authSetting = {
            "scope.userInfo": true,
            "scope.userLocation": true,
            "scope.address": true
          }
          // that.wechatSq();
          // //尝试再次登录
          if (again) {
            wx.navigateBack({
              delta: 1
            })
          } else {
            // wx.reLaunch({
            //   url: '/pages/singlePage/singlePage',
            // })
            that.wechatSq();
          }
        }
      })
    } else {
      wx.showModal({
        title: '授权提示',
        content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：1、请10分钟后再次点击授权。 2、删除小程序->重新搜索进入->点击授权按钮。'
      })
    }
  },
  //设置导航条字样
  setNavtitle: function (name) {
    var that = this;
    var path = getCurrentPages()[getCurrentPages().length - 1].__route__;
    var menu = that.globalData.menuTitle;
    var title = name;
    if (!menu) {
      title = name;
    } else {
      if (!menu[path]) {
        title = name;
      } else {
        title = menu[path];
      }
    }
    console.log(title);
    wx.setNavigationBarTitle({
      title: title
    })
  },
  // 设置导航菜单
  setPageviewlink: function (obj, link) {
    var that = this;
    var path = getCurrentPages()[getCurrentPages().length - 1].__route__;
    var menu = that.globalData.pageviewlink;
    var pageviewlink = link;
    if (!menu) {
      pageviewlink = link;
    } else {
      if (!menu[path]) {
        pageviewlink = link;
      } else {
        pageviewlink = menu[path];
      }
    }
    console.log(pageviewlink);
    if (!pageviewlink) {
      wx.showModal({
        title: '提示',
        content: '后台暂未配置页面链接',
        showCancel: false
      })
    }
    obj.setData({
      tempid: pageviewlink
    })
  },
  // 上传图片选择
  chooseImageTap: function (that, length, index) {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that, length, index)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, length, index)
          }
        }
      }
    })

  },
  chooseWxImage: function (type, that, length, index) {
    var _this = this;
    wx.chooseImage({
      count: length,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        var temPaths = res.tempFilePaths;
        that.setData({
          temPaths: temPaths
        });
        that.uploadImage(index);
      }
    })
  },
  splitArrData: function (arr, pageNum) {
    var i = 0;
    var page = Math.ceil(arr.length / pageNum);
    var newArr = [];
    for (var i = 0; i < page; i++) {
      var curarr = [];
      curarr = arr.slice(i * pageNum, (i * pageNum + pageNum));
      console.log(page);
      newArr.push(curarr);
    }
    console.log(newArr);
    return newArr;
  },
  // 暂停播放背景音乐
  toggleInfoPlay: function (that) {
    var _this = this;
    var isPlay = that.data.isPlay;
    console.log("切换资讯背景音乐");
    console.log(isPlay);
    if (isPlay) {
      bgMusicAudioContext.pause();
      isPlay = false;
      _this.globalData.musicPlay = false;
    } else {
      if (_this.globalData.isPlaynew == 'new') {
        console.log("新音乐播放");
        bgMusicAudioContext.stop();
        bgMusicAudioContext.src = _this.globalData.musicUrl;
        bgMusicAudioContext.coverImgUrl = _this.globalData.playMusicCover;
        bgMusicAudioContext.title = _this.globalData.musicName;

        _this.globalData.curInfoMusicid = _this.globalData.playMusicid;
        _this.musicProgress(bgMusicAudioContext, that);
        _this.globalData.isPlaynew = '';
      } else {
        bgMusicAudioContext.play();
        _this.musicProgress(bgMusicAudioContext, that);
      }
      isPlay = true;
      _this.globalData.musicPlay = true;
    }
    that.setData({
      isPlay: isPlay
    })
    _this.globalData.isPlay = isPlay;
    that.musicOpera();
  },
  // 音乐播放进度
  musicProgress: function (bgMusicAudioContext, that) {
    var _this = this;
    bgMusicAudioContext.onTimeUpdate(function () {
      var curTime = Math.ceil(bgMusicAudioContext.currentTime);
      var sumTime = Math.ceil(bgMusicAudioContext.duration);
      var curPlaytime = _this.formatPlayTime(curTime);
      var durationTime = _this.formatPlayTime(sumTime);
      that.setData({
        curTimeStep: curTime,
        curPlaytime: curPlaytime,
        sumPlayTime: sumTime,
        durationTime: durationTime,
        playProgressDis: false
      })
      _this.globalData.isReplay = '';
    });
    bgMusicAudioContext.onError(function () {
      console.log("播放错误")
      that.setData({
        isPlay: false
      })
      app.globalData.isPlay = false;
      app.globalData.curInfoMusicid = '';
    });
    bgMusicAudioContext.onEnded(function () {
      console.log("播放自然结束");
      var sumTime = Math.ceil(bgMusicAudioContext.duration);
      var durationTime = _this.formatPlayTime(sumTime);
      that.setData({
        curTimeStep: 0,
        isPlay: false,
        curPlaytime: '0:00',
        sumPlayTime: 100,
        durationTime: durationTime,
        playProgressDis: true
      })
      console.log(that.data);
      _this.globalData.isPlay = false;
      _this.globalData.isReplay = 'reply';
      _this.globalData.isPlaynew = 'new'
    })
  },
  // 格式化音乐进度显示时间
  formatPlayTime: function (time) {
    var minute = parseInt(time / 60);
    var second = parseInt((time % 60));
    second = second < 10 ? '0' + second : second;
    var showTime = minute + ':' + second;
    return showTime;
  },
  // 计算两点之间距离
  getFlatternDistance: function (lat1, lng1, lat2, lng2) {
    var that = this;
    var f = that.getRad((lat1 + lat2) / 2);
    var g = that.getRad((lat1 - lat2) / 2);
    var l = that.getRad((lng1 - lng2) / 2);
    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);
    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;
    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;
    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;
    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;
    return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg)) / 1000;
  },
  getRad: function (d) {
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
  },
  // 根据距离给列表排序
  sortArr: function (property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  },
  // 获取当前定位地址
  getCurAddress: function (lat, lng, obj) {
    var that = this;
    wx.request({
      url: that.globalData.requestUrl,
      data: {
        map: 'applet_get_address',
        lat: lat,
        lng: lng
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res);
          obj.setData({
            curLocation: res.data.data.address
          })
        } else {
          that.errorTip(obj, res.data.em, 2000);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  setNavColor: function (obj) {
    var that = this;
    var navColor = '#ff8132';
    if (that.globalData.navBgcolor && that.globalData.navTextStyle == 'white') {
      navColor = that.globalData.navBgcolor;
    }
    obj.setData({
      navColor: navColor
    })
    console.log("导航颜色" + obj.data.navColor);
  },
  setPhoneopen: function (obj) {
    var that = this;
    obj.setData({
      phoneOpen: that.globalData.phoneOpen ? that.globalData.phoneOpen : 0
    })
    console.log("是否显示拨打电话" + obj.data.phoneOpen);
  },
  // 广告数据
  requestAd: function (obj) {
    var _this = this;
    var that = obj;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_city_advertisement_cfg'
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          var randomIndex = Math.round(Math.random() * (10 - 1) + 1) - 1;
          that.setData({
            adInfo: res.data.data,
            randomIndex: randomIndex
          })
        } else {
          console.log(res.data)
        }
      },
      complete: function () {
      }
    });
  },
  getContactCfg: function () {
    var _this = this;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_kefu_cfg'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log('获取客服配置信息', res.data.data);
          wx.setStorage({
            key: 'contactCfg',
            data: res.data.data,
            success: function (res) {
              console.log('存储成功');
              if (_this.globalData.againRequestContact && getCurrentPages()) {
                var page = getCurrentPages()[getCurrentPages().length - 1];   //获取当前页面指针 
                _this.contactData(page);
                _this.globalData.againRequestContact = false;
              }
            },
            fail: function () {
              console.log('存储失败');
            }
          })
        } else {
        }
      },
      complete: function () {

      }
    });
  },
  //客服验证绑定手机号
  contactData: function (that) {
    var _this = this;
    var data = wx.getStorageSync('contactCfg')
    if (data) {
      console.log('获取到客服缓存配置', data);
      that.setData({
        kefuSetting: data
      })
    } else {
      console.log('重新获取客服缓存配置');
      _this.globalData.againRequestContact = true;
      _this.getContactCfg();
    }
  },
  contactRecord: function (e) {
    var _this = this;
    wx.request({
      url: _this.globalData.requestUrl,
      data: {
        map: 'applet_kefu_click'
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log(res.data.data);
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
    console.log(e);
    if (e.detail.path) {
      let navUrl = e.detail.path + "?";
      for (let i in e.detail.query) {
        navUrl += (i + '=' + e.detail.query[i] + '&');
      };
      console.log(navUrl);
      wx.navigateTo({
        url: navUrl,
      })
    }
  },
  getPhone: function (e, that) {
    var _this = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var data = {
            map: 'applet_bind_member_mobile',
            code: res.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          };
          if (data.encryptedData && data.iv) {
            _this.requestMobile(that, data);
          }
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  requestMobile: function (that, data) {
    console.log(data);
    var _this = this;
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    console.log(_this.globalData.requestUrl);
    console.log(data);
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log(res.data.data);
          _this.globalData.contactPhone = res.data.data;
          that.setData({
            contactPhone: res.data.data
          })
        } else {
          _this.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
  },
  isAudit: function (that, url, func) {
    var _this = this;
    // var indexUrl = '';
    // if (url) {
    //   indexUrl = decodeURIComponent(url);
    // }
    // 判断是否验证
    var data = {
      map: 'applet_start_page'
    }
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: _this.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log("审核页面")
        console.log(res.data.data);
        var applyInfo = res.data.data;
        that.setData({
          applyInfo: applyInfo,
          applyStatus: applyInfo.applyStatus
        })
        console.log("验证状态" + (applyInfo.applyStatus == 2))
        if (applyInfo.applyOpen == 1) {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        } else {
          if (func) {
            func();
          }
        }
        // if (applyInfo.applyStatus == 2) {
        //   // var indexUrl = applyInfo.indexUrl;
        //   // if (url){
        //   //   indexUrl = decodeURIComponent(url);
        //   // }
        //   // console.log("审核前页面路径" + indexUrl)
        //   // wx.reLaunch({
        //   //   url: indexUrl
        //   // })
        //   if(func){
        //     func();
        //   }
        // }
        // var applyTtitle = applyInfo.applyTtitle ? applyInfo.applyTtitle : '申请验证';
        // console.log(applyTtitle);
        // _this.setNavtitle(applyTtitle);
      },
      fail: function (res) {
        console.log(res.data);
        _this.errorTip(that, res.data.em, 2000);
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  setCartnum: function () {
    var that = this;
    if (!that.globalData.plumSession) return;
    var menu = that.globalData.menuTitle;
    var cartIndex = '';
    cartIndex = that.globalData.cartIndex;
    console.log("当前购物车索引");
    if (!menu) {
      cartIndex = 1;
    }
    console.log(cartIndex);
    if (cartIndex != '') {
      console.log('购物车数量11111111', that.globalData.requestCartNum);
      if (that.globalData.requestCartNum >= 0) {
        if (that.globalData.requestCartNum > 0) {
          wx.setTabBarBadge({
            index: cartIndex,
            text: that.globalData.requestCartNum.toString()
          });
        } else if (that.globalData.requestCartNum == 0) {
          wx.removeTabBarBadge({
            index: cartIndex
          })
        }
        return;
      }
      wx.request({
        url: that.globalData.requestUrl,
        data: {
          map: 'applet_cart_num'
        },
        success: function (res) {
          // console.log(res.data.data.cartNum);
          var cartNum = res.data.data ? res.data.data.cartNum : 0;
          if (cartNum > 0) {
            wx.setTabBarBadge({
              index: cartIndex,
              text: cartNum.toString()
            })
          } else {
            wx.removeTabBarBadge({
              index: cartIndex
            })
          }
        },
        fail: function (res) {
          console.log(res.data);
        },
      });
    }
  },
  // 返回首页跳转判断
  backHome: function () {
    var _this = this;
    var pathArr = getCurrentPages();
    if (pathArr.length <= 1) {
      wx.reLaunch({
        url: '/pages/singlePage/singlePage'
      })
    } else {
      if (_this.globalData.homePath) {
        _this.getHomepath(pathArr);
      } else {
        wx.request({
          url: _this.globalData.requestUrl,
          data: {
            map: 'applet_index_page',
            appletType: 1
          },
          success: function (res) {
            var homePath = res.data.data.path;
            console.log(homePath);
            _this.globalData.homePath = homePath;
            _this.getHomepath(pathArr);
          }
        });
      }
    }
  },
  // 返回首页获取配置首页路径跳转
  getHomepath: function (pathArr) {
    var _this = this;
    var ishasHome = false;
    var homePath = _this.globalData.homePath;
    for (let i = 0; i < pathArr.length; i++) {
      if (pathArr[i].__route__ == homePath) {
        ishasHome = true;
      }
    }
    console.log(ishasHome);
    if (ishasHome) {
      wx.navigateBack({
        delta: 10
      })
    } else {
      wx.switchTab({
        url: '/' + homePath
      })
    }
  },
  getUnionid: function (that, userdata) {
    var _this = this;
    wx.login({
      success(res) {
        if (res.code) {
          var data = {
            map: 'applet_get_member_unionid',
            code: res.code,
            iv: userdata.iv,
            encryptedData: userdata.encryptedData
          };
          console.log(data);
          //发起请求，获取列表列表
          wx.request({
            url: _this.globalData.requestUrl,
            data: data,
            success: function (res) {
              console.log(res.data);
              if (res.data.ec == 200) {
                _this.globalData.isHasunionid = 1;
                if (that) {
                  that.setData({
                    isHasunionid: _this.globalData.isHasunionid
                  })
                }

              } else {
              }
            },
            complete: function () {
            }
          });
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  requestIndex: function (type) {
    var that = this;
    wx.request({
      url: that.globalData.requestUrl,
      data: {
        map: 'applet_index_info',
        version: that.globalData.version,
        base: that.globalData.base,
        couponIndex: 0
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.globalData.distribOpen = res.data.data.distribOpen;
          var sharedata = {
            shareOpen: res.data.data.shareOpen,
            shareUrl: res.data.data.shareUrl,
            shareTitle: res.data.data.template.title
          }
          that.globalData.sharedata = sharedata;
          // 存储是否开启客服
          that.globalData.customerService = res.data.data.customerService;
          if (res.data.data.customerService == 1) {
            var sessionForm = {
              "nickName": that.globalData.userInfo.nickName,
              "city": that.globalData.userInfo.city
            }
            that.globalData.sessionForm = JSON.stringify(sessionForm);
          }
          // 设置电话
          that.globalData.telphone = res.data.data.mobile;
          that.globalData.phoneOpen = res.data.data.phoneOpen;
          var namelogo = {
            name: res.data.data.name,
            logo: res.data.data.logo
          };
          that.globalData.namelogo = namelogo;
          var shareInfo = {
            shareCover: res.data.data.shareCover,
            shareTitle: res.data.data.shareTitle
          }
          that.globalData.shareInfo = shareInfo;
          var shopname = res.data.data.name;
          wx.setStorage({
            key: "shopInfoname",
            data: shopname,
            success: function (e) {
              console.log("存储成功")
            }
          })
        } else {
        }
      },
      complete: function () {
      }
    });
  },
  //订阅消息，获取模版id
  getSubId: function (obj, operate, fun) {
    var that = this;
    console.log(operate);
    var tmplIdsArr = Object.keys(that.globalData.requestTmplIds);
    console.log(tmplIdsArr.length)
    if (that.globalData.requestTmplIds && tmplIdsArr.length > 0) {
      var tmplData = that.globalData.requestTmplIds;
      var tmplIds = [];
      tmplIds = tmplData[operate];
      if (wx.canIUse('requestSubscribeMessage')) {
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            console.log('调起成功', res);
            var ids = [];
            for (let key in res) {
              console.log(key, res[key]);
              console.log(res[key]);
              if (res[key] == 'accept') {
                ids.push(key);
              }
            }
            if (ids.length > 0) {
              that.saveSubId(ids); //存储同意的ids
            }
          },
          fail(res) {
            console.log('调起失败', res);
          },
          complete() {
            obj[fun]();
          }
        })
      } else {
        obj[fun]();
      }
    } else {
      obj[fun]();
    }
  },
  //处理保存同意发送消息的id
  saveSubId: function (ids) {
    var that = this;
    var saveTmplNum = that.globalData.saveTmplNum;
    var saveTmplArr = that.globalData.saveTmplArr;
    console.log(saveTmplNum);
    if (saveTmplNum > 10) {
      that.toSaveSubId();//执行保存操作
    } else {
      saveTmplNum += 1;
      that.globalData.saveTmplNum = saveTmplNum;
      var tmplArr = that.globalData.saveTmplArr;
      console.log(tmplArr);
      for (let i = 0; i < ids.length; i++) {
        let keyIndex = -1;
        for (let key in tmplArr) { //判断之前存储的数组是否含有这个订阅id
          if (key == ids[i]) {
            keyIndex = ids[i];
          }
        }
        if (keyIndex != -1) { //之前存在的订阅id累加1
          tmplArr[keyIndex] += 1;
        } else { //不存在的新增一项
          tmplArr[ids[i]] = 1;
        }

      }
      console.log(tmplArr);
      that.globalData.saveTmplArr = tmplArr;
    }
  },
  //保存同意发送消息的id
  toSaveSubId: function () {
    var that = this;
    console.log('保存订阅id');
    var saveTmplArr = that.globalData.saveTmplArr;
    var saveTmplArrLen = Object.keys(saveTmplArr);
    if (saveTmplArrLen.length > 0) {
      console.log('执行保存订阅id');
      wx.request({
        url: that.globalData.requestUrl,
        data: {
          map: 'applet_subscribe_save_auth',
          tplIds: JSON.stringify(saveTmplArr)
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            console.log('保存订阅消息成功');
            that.globalData.saveTmplNum = 0;
            that.globalData.saveTmplArr = {};
          } else {
            console.log('保存订阅消息失败1');
          }
        },
        fail: function (res) {
          console.log('保存订阅消息失败2');

        },
        complete: function () {
        }
      });
    }
    console.log(that.globalData.saveTmplArr);
  },
  // 更新后台直播状态
  updateLiveStatus: function (roomId, liveStatus) {

    wx.request({
      url: this.globalData.liverqurl,
      data: {
        map: 'applet_appletlive_update_status',
        room_id: roomId,
        status: liveStatus
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log('更新直播状态成功');

        } else {
          console.log('更新直播状态失败');
        }
      },
      fail: function (res) {


      },
      complete: function () {
      }
    });
  },
  // 通用调起微信支付
  commonRequestPayment(params) {
    return new Promise(function (resolve, reject) {
      wx.requestPayment({
        ...params,
        'success': function (res) {
          resolve(res)
        },
        'fail': function (res) {
          reject(res)
          console.log(res);
        }
      });
    })
  },
  //计算导航栏高度
  calNavBarHeight: function (obj) {
    let systemInfo = wx.getSystemInfoSync();
    console.log(systemInfo);
    let rect;
    try {
      rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null; //胶囊按钮位置信息
      if (rect === null) {
        throw 'getMenuButtonBoundingClientRect error';
      }
    } catch (error) {
      let gap = ''; //胶囊按钮上下间距 使导航内容居中
      let width = 96; //胶囊的宽度，android大部分96，ios为88
      if (systemInfo.platform === 'android') {
        gap = 8;
        width = 96;
      } else if (systemInfo.platform === 'devtools') {
        if (systemInfo.platform === 'ios') {
          gap = 5.5; //开发工具中ios手机
        } else {
          gap = 7.5; //开发工具中android和其他手机
        }
      } else {
        gap = 4;
        width = 88;
      }
      if (!systemInfo.statusBarHeight) {
        //开启wifi的情况下修复statusBarHeight值获取不到
        systemInfo.statusBarHeight = systemInfo.screenHeight - systemInfo.windowHeight - 20;
      }
      rect = {
        //获取不到胶囊信息就自定义重置一个
        bottom: systemInfo.statusBarHeight + gap + 32,
        height: 32,
        left: systemInfo.windowWidth - width - 10,
        right: systemInfo.windowWidth - 10,
        top: systemInfo.statusBarHeight + gap,
        width: width
      };
      console.log('error', error);
      console.log('rect', rect);
    };

    let navBarHeight = (function () { //导航栏高度
      let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
      return 2 * gap + rect.height;
    })();
    var barPaddingTop = systemInfo.statusBarHeight;
    var iconTop = (navBarHeight - 30) / 2 + barPaddingTop
    obj.setData({
      navBarHeight: navBarHeight, //navBar的高
      barPaddingTop: barPaddingTop, //navBar的padding-top值
      iconTop: iconTop
    })
    console.log(navBarHeight);
  }
})

